﻿(async () => {
    await window.ris.initialize();

    $(() => {
        const $eventEmitter = $('body > .container');

        let reloadGrid = null;
        let exportParams = null;
        let exportData = (func) => {
            if (func instanceof Function) {
                func(exportParams);
            }
        };
        $('.main').splitter({
            orientation: 'v',
            panel1Size: '300px',
        });
        const quickFilter = $('.quick-filter').quickFilter(
            `/api/filter/get-filter-by-type/appointment`,
            filterId => {
                reloadGrid = () => {
                    dataGrid.reload({ filterId });
                };
                reloadGrid();
            },
            {
                type: 'GET',
            }
        );
        const advancedSearch = $('.advanced-search').advancedSearchWithCollapse(null, (e) => {
            reloadGrid = () => {
                dataGrid.refresh({ userData: e });
            };
            reloadGrid();
        }, { id: 'register' });

        const gridOperations = [];
        const gridContextMenuItems = [];
        const dataGrid = $('.exam-grid').examGrid({
            id: 'register-exam-grid',
            key: 'oid',
            getOperations() {
                return gridOperations;
            },
            getContextMenuItems() {
                return gridContextMenuItems;
            },
            onLoad(loadOptions) {
                return new Promise((resolve, reject) => {
                    if (loadOptions.filterId || (loadOptions.userData && !$.isEmptyObject(loadOptions.userData))) {
                        exportParams = loadOptions;
                        $.post({
                            dataType: 'json',
                            contentType: 'application/json;charset=UTF-8',
                            url: `/api/register/get-list`,
                            data: JSON.stringify(loadOptions),
                            success: result => {
                                if (result.success) {
                                    resolve(result)
                                } else {
                                    reject(result.error);
                                }
                            }
                        });
                    } else {
                        resolve({ success: true, data: { columns: [], rows: [], totalCount: 0 } })
                    }
                })
            },
            onRowDblClick(oid) {
                window.open(`/register/detail?oid=${encodeURIComponent(oid)}`, '_blank');
            }
        });

        const toolbar = $('.toolbar').dxToolbar({}).dxToolbar('instance');
        const toolbar1 = $('.toolbar1').dxToolbar({}).dxToolbar('instance');
        Promise.all([$.get(`/api/get-device-type-options`), $.get('/api/get-interface-service'), $.get('/api/get-print-options')]).then((result) => {
            // 1、根据科室获取设备类型
            let deviceType = undefined
            if (result[0].success) {
                deviceType = result[0].data;
            }
            // 2、获取数据来源
            let dataSource = [];
            if (result[1].success) {
                dataSource = result[1].data;
            }
            // 3、打印列表
            let printOptions = [];
            if (result[2].success) {
                printOptions = result[2].data;
            }
            const tools = $.getRegisterTools($eventEmitter, quickFilter, advancedSearch, dataGrid, null, null, {
                deviceType,
                dataSource,
                reloadGrid: () => {
                    if (reloadGrid instanceof Function) {
                        reloadGrid();
                    }
                },
                exportData: (func) => {
                    if (exportData instanceof Function) {
                        exportData(func);
                    }
                }
            });
            //设置列表操作列
            setGridOperations(tools);
            //等候队列
            setWaitingQueue(tools);
            //设置新建操作
            let defaultOption = tools.new;
            if (!deviceType) {
                defaultOption.disabled = true;
            }
            else {
                defaultOption = setNew(defaultOption, deviceType, tools);
            }
            //打印，要兼容右键菜单
            if (printOptions instanceof Array && printOptions.length > 0) {
                printOptions = printOptions.filter(option => option.id !== 'TempReport');
                printOptions.forEach(e => {
                    e.icon = 'print';
                    e.onClick = (e) => {
                        $eventEmitter.trigger('print', {
                            quickFilter,
                            advancedSearch,
                            examGrid: dataGrid,
                            data: e.itemData
                        });
                    };
                });
                tools.print.options.items = printOptions;
            }
            setToolbar(toolbar, defaultOption, tools);
            setToolbar1(toolbar1, tools, dataSource);
            setGridContextMenu(tools);
        });


        $.get('/api/register/get-advanced-search-view').then(result => {
            if (result.success) {
                if (result.view) {
                    advancedSearch.updateView(result.view, result.data);
                }
            }
        });

        const setGridOperations = (tools) => {
            gridOperations.push({
                ...tools.open, options: {
                    ...tools.open.options,
                    text: '打开患者',
                    beginGroup: true
                }
            }, {
                ...tools.delete, options: {
                    ...tools.delete.options,
                    text: '删除患者',
                    beginGroup: true
                }
            }, {
                ...tools.viewReport, options: {
                    ...tools.viewReport.options,
                    text: '查看报告',
                    beginGroup: true
                }
            }, {
                ...tools.viewImage, options: {
                    ...tools.viewImage.options,
                    text: '查看图像'
                }
            }, {
                ...tools.arrival, options: {
                    ...tools.arrival.options,
                    text: '患者到诊',
                    beginGroup: true
                }
            }, tools.top, tools.applyConsultation);
        }

        const setWaitingQueue = (tools) => {
            tools.waitingQueue.options.items = [tools.suspend.options, tools.cancelSuspend.options, tools.top.options, tools.previous.options, tools.next.options, tools.bottom.options]
        }

        const setNew = (defaultOption, deviceType, tools) => {
            if (deviceType instanceof Array && deviceType.length > 1) {
                defaultOption = tools.deviceTypeSelect;
                defaultOption.options.items = deviceType;
                return defaultOption;
            }
            return defaultOption;
        }

        const setToolbar = (toolbar, defaultOption, tools) => {
            //判断是否已经启用了自动刷新
            tools.autoRefresh.options.text = autoRefresh('registerRefreshInterval', 'registerInterval', () => {
                if (reloadGrid instanceof Function) {
                    reloadGrid();
                }
            }, true);
            tools.refreshSetting.options.items = [tools.autoRefresh.options, tools.refreshInterval.options]
            let beforeTools = [defaultOption, tools.open, tools.delete, tools.print, tools.viewReport, tools.viewImage, tools.arrival, tools.waitingQueue, tools.study, tools.greenChannel];
            //其他操作
            tools.others.options.items = [];
            let afterTools = [tools.others, tools.refresh, tools.refreshSetting];
            let toolbarOptions = [...beforeTools, ...afterTools];
            toolbar.option('items', toolbarOptions);
        }
        const setToolbar1 = (toolbar, tools, dataSource) => {
            tools.dataSourceSelect.options.items = dataSource;
            if (dataSource && dataSource instanceof Array && dataSource.length > 0) {
                localStorage.setItem('selected-dataSource', dataSource[0].id);
                tools.dataSourceSelect.options.value = localStorage.getItem('selected-dataSource');
            }
            toolbar.option('items', [tools.dataSourceSelect, tools.idCard, tools.medicareCard, tools.medicalCard, tools.scanCode, tools.supplementarySync, tools.search, tools.customQuery]);
        }
        const setGridContextMenu = (tools) => {
            gridContextMenuItems.push({
                ...tools.open, options: {
                    ...tools.open.options,
                    text: '打开患者',
                }
            }, {
                ...tools.delete, options: {
                    ...tools.delete.options,
                    text: '删除患者',
                }
            }, {
                ...tools.print, options: {
                    ...tools.print.options,
                    text: '打印单据',
                }
            }, tools.viewReport, tools.viewImage, tools.examEvent, tools.export,
                tools.refund, tools.arrival, tools.waitingQueue, tools.applyConsultation);
        }
    });
})();
